--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local log = require "Logger"
local config = require "configquery"
local ProtoLoader = require "ProtoLoader"
local RoomConfig = require "RoomConfig"


local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch, node_message)
	self.game_code = skynet.getenv("game_code") --服务代号
	self.proto_file = skynet.getenv("proto_config") --proto文件路径	
    self.server_id = tonumber(skynet.getenv("server_id"))
    self.server_type = skynet.getenv("server_type") 
    self.server_name = skynet.getenv("server_name") 
    self.cluster_addr = skynet.getenv("cluster_addr")
    self.cluster_name = skynet.getenv("cluster_name")
    self.server_name = skynet.getenv("server_name")
    self.zone_cluster_id = skynet.getenv("zone_cluster_id")
    self.node_cluster_id = skynet.getenv("node_cluster_id")

	self.message_dispatch = message_dispatch
	self.node_message = node_message
	self.proto_loader = ProtoLoader.new() --proto加载
    self.room_config = {} --所有场次配置
    self.services = {} --所有桌子服务

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	--启动
	self.message_dispatch:registerSelf('start', handler(self,self.start))
	self.message_dispatch:registerSelf('server_register_res', handler(self,self.serverRegisterRes))
    self.message_dispatch:registerSelf('dispatch', handler(self,self.dispatch))

    
end

-- 向节点服务器注册
function MessageHandler:serverRegisterReq()
    local server_info = {
        server_id = self.server_id,
        server_type = self.server_type,
        server_name = self.server_name,
        cluster_addr = self.cluster_addr,
        cluster_name = self.cluster_name,
    }
    print("_____发送注册____")
    self.node_message:sendNodeProxy(self.node_cluster_id, "server_register_req", server_info)     
end


--加载配置
function MessageHandler:loadConfig()
    -- 数据库加载配置
    local server_type = self.server_type
    local server_id = self.server_id
    local sql = "select s.server_id, s.type, s.max_client, gr.* from server_list s, game_config gr where s.game_id=gr.game_id and s.server_id=" .. server_id
    local tb_config = self.node_message:callDbProxy("executeMySql", sql)        
    -- print("____tb_config___",tb_config)
    for k, config in pairs(tb_config) do 
        local room_config = RoomConfig.new() --场次配置
        room_config:init(config)
        self.room_config[config.group_id] = room_config
    end
    self.room_manager:setRoomConfig(self.room_config)
end

--创建房间(场次)
function MessageHandler:createRoom()
    for k, room_config in pairs(self.room_config) do 
        -- local game_code = v:getGameCode()
        self:createDesks(room_config)
    end
end

--创建桌子 int64
--desk_id=time(8)+game_id(2) + group_id(1) + index
--
function MessageHandler:createDesks(room_config)
  
    local room_data = room_config:getData()
    local desk_count = room_config:getDeskCount()
    local seat_count = room_config:getSeatCount()
    local game_id = room_config:getGameId()
    local group_id = room_config:getGroupId()
    local player_count = room_config:getPlayerCount()
    -- print("_____createDesks________",desk_count, seat_count)
    local time = os.date("%d%H%M%S",os.time())    
    local desk_str = string.format("%s%02d%d",time,game_id,group_id)
    for i = 1, desk_count do
        -- local desk_service = skynet.newservice(service_name, self.desk_index, seat_count)
        local desk_info = {
            desk_id = tonumber(string.format("%s%d",desk_str,i)),
            desk_service = nil, --用到时再创建 
            seat_count = seat_count, 
            player_count = player_count, 
            game_id = game_id, 
            group_id = group_id,
        }        
        self.room_manager:addDesk(desk_info)
        -- self.node_message:callService(desk_service, "init", room_config, self.pbc_env)
    end
end

--发送服务器信息
function MessageHandler:sendServerInfo()
   local server_info = {
        server_id = self.server_id,
        server_type = self.server_type,
        server_name = self.server_name,
        cluster_addr = self.cluster_addr,
        cluster_name = self.cluster_name,        
        max_client = self.server_manager:getMaxClient(),
        online_count = self.server_manager:getOnlineCount(),    
        server_addr = self.server_addr,  
    }   
    self.node_message:sendNodeProxy(self.zone_cluster_id, "server_info_nt", server_info)
end

--发送房间信息到zone
function MessageHandler:sendRoomInfo()
    log.debug("handle room info............")
    --房间信息
    local room_config = self.room_manager:getRoomConfig()
    local groups = {}
    for k,v in pairs(room_config) do 
        local group = {
            game_id = v:getGameId(),
            group_id = v:getGroupId(),
            game_genre = v:getGameGenre(),
            dynamic_join = v:isDynamicJoin() == true and 1 or 0,
            server_rule = v:getServerRule(),
            desk_count = v:getDeskCount(),
            seat_count = v:getSeatCount(),
        } 
        groups[group.group_id] = group  
    end
    groups.server_id = self.server_id
    groups.server_type = self.server_type
    -- print("___groups__",groups)
    --发送在线信息
    self.node_message:sendNodeProxy(self.zone_cluster_id, "room_info_nt", groups)        
    --所有桌子信息
    self:sendRoomAllDeskInfo()
end

--发送桌子信息到zone
function MessageHandler:sendRoomAllDeskInfo()
    log.debug("handle room all desk info............")
    --桌子信息
    local desk_list = self.room_manager:getDeskList()
    -- print("__desk_list__",desk_list)
    for _, desk in pairs(desk_list) do
        local desk_info = {
            server_id = self.server_id,
            server_type = self.server_type,
            game_id = desk.game_id,
            group_id = desk.group_id,
            desk_id = desk.desk_id,
            player_count = desk.player_count,
            sit_down_count = desk.sit_down_count or 0,
            game_started = desk.game_started or 0,
        }
        --发送在线信息（如果桌子多会不会一下子发送过多消息包， 后面要优化
        self.node_message:sendNodeProxy(self.zone_cluster_id, "desk_info_nt", desk_info)         
    end
end




------------------------------------------------------------------
--cmd
------------------------------------------------------------------
function MessageHandler:start()
	-- local pbc_env = self.proto_loader:init(self.proto_file, {'common','game','gate','web','zone','hall',})
    self.server_manager = global.server_manager
    self.game_config = global.game_config
    self.room_manager = global.room_manager

	--初始化
	-- self.node_message:initProto(pbc_env)
	--skynet控制台
	-- skynet.newservice("debug_console", svr_config.debug_port)
	self:serverRegisterReq()


end

--nodeserver 返回注册成功
function MessageHandler:serverRegisterRes(msg_data)
    -- print("__serverRegisterRes___",msg_data)
    self:sendServerInfo()
    self:loadConfig()
    self:createRoom()
    self:sendRoomInfo()
end

--派发消息到游戏桌子中
function MessageHandler:dispatch(cmd, ...)
    print("_____gameserver__收到dispatch___", cmd, ...)
    local msg_data = ...
    local desk_id = msg_data.desk_id 
    local service = self.services[desk_id]    
    if cmd=="enterDeskReq" and service==nil then                
        local room_config = self.room_manager:getRoomConfigByDesk(desk_id)
        local desk_config = self.room_manager:getDesk(desk_id) 
        local name = room_config:getGameCode().."_service"
        service = skynet.newservice(name)
        if service then 
            self.services[desk_id] = service
            self.node_message:callService(service, "init", room_config:getData(), desk_config)
        end
    end    
    if service then 
        --传到游戏服务中
        local res = self.node_message:callService(service, cmd, ...)
        if res and next(res) then 
            return res
        end
    end
    --本服务处理
    return self.message_dispatch:dispatchSelfMessage(cmd, ...)
end




return MessageHandler